package com.tools.cleanmaster.ui.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.hm.base.android.mob.RunAsyncTask;
import com.tools.ad.EntranceType;
import com.tools.ad.util.StatusBarUtil;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.appinfo.AppInfoCompat;
import com.tools.cleanmaster.appinfo.AppManagerCompat;
import com.tools.cleanmaster.functionpage.FunctionItemSharedPrefs;
import com.tools.cleanmaster.scenenew.SceneType;
import com.tools.cleanmaster.store.ResultPageSharedPrefManager;
import com.tools.cleanmaster.taskmain.ProcessItem;
import com.tools.cleanmaster.taskmain.TKPubApi;
import com.tools.cleanmaster.ui.base.ResultSingleActivity;
import com.tools.cleanmaster.ui.card.animator.AnimationListenerAdapter;
import com.tools.cleanmaster.ui.card.factory.CardDataHelper;
import com.tools.cleanmaster.ui.card.newresult.NewResPageUtils;
import com.tools.cleanmaster.ui.card.ui.ResultSingleCardLayout;
import com.tools.cleanmaster.ui.notification.NotificationBaseItem;
import com.tools.cleanmaster.ui.utils.LottieAnimationUtil;
import com.tools.cleanmaster.ui.view.LoadingInsideLayout;
import com.tools.cleanmaster.ui.view.header.HeadHelper;
import com.tools.cleanmaster.ui.view.landingpage.LandingPageRunAppBackView;
import com.tools.cleanmaster.utils.MemoryUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 通知栏点击后的显示页面（低电量，耗电过高，后台耗流量，CPU使用量和内存使用量等通知）
 * Created by wen.yu.gang on 18/6/22.
 */
@SuppressLint("MissingPermission")
public class LandingPageGuideActivity extends ResultSingleActivity implements View.OnClickListener {
    private static final int PRO_FOUND = 11;
    private static final int MORE_SUGGESTION = 12;
    private static final int MULTI_APP_STYLE = 1;
    private static final int SINGLE_APP_STYLE = 2;
    public static final String SINGLE_PKG = "pkg";

    private int mCurLayoutStyle;
    protected SceneType mCurSceneType;
    private String mFuncText;
    private String mFuncTipText;
    private String mSingleAppTip;
    private int mFuncIconId;
    private AppInfoCompat mCurSingleApp;
    private List<ProcessItem> mCurMultiApps;

    private View mBottomBtn;
    private LoadingInsideLayout mLoadingProgress;

    // RunAppView展示
    private LandingPageRunAppBackView mRunAppBackView;
    private LinearLayout mFeatureContainer;
    private FrameLayout mGuideContainer;
    private View mSingleTopContainer;

    // loading card 对勾
    private View mPerfectFrameLayout;
    private LottieAnimationView mPerfectView;

    private ImageView mFuncIconView;
    private TextView mFuncTextView;
    private TextView mFuncTipsView;
    private long liveTime;

    @Override
    protected void setCardHeadTitle() {
        if (mResultMultiCardLayout != null) {
            mResultMultiCardLayout.setHeadTitle(getString(R.string.landingpage_header_title));
        }
    }

    @Override
    protected void hideBackground() {
        mFeatureContainer.setVisibility(View.GONE);
    }

    @Override
    protected EntranceType getEntranceType() {
        return EntranceType.LANDING;
    }

    @Override
    public ResultPageType getResultPageType() {
        return ResultPageType.MultiCardPage;
    }

    @Override
    protected void setContentView(Bundle savedInstanceState) {
        setContentView(R.layout.landing_page_guide_layout);
        StatusBarUtil.setTranslucent(this, 0);
        liveTime = System.currentTimeMillis();

        initViews();
        showProgressLoading();
        initData();
        handleTopContentData();
    }

    private void initData() {
        String sceneKey = getIntent().getStringExtra(NotificationBaseItem.SCENE_TYPE_EXTRA_FLAG);
        mCurSceneType = SceneType.getTypeByKey(sceneKey);
        if (mCurSceneType != null) {
            if (SceneType.NETFRQ_SCREENOFF == mCurSceneType) {
                mCurLayoutStyle = SINGLE_APP_STYLE;
                String pkg = getIntent().getStringExtra(SINGLE_PKG);
                scanExistSingleApp(pkg);
            } else {
                mCurLayoutStyle = MULTI_APP_STYLE;
                scanExistMultiApp();
            }
        }
    }

    /**
     * 多卡片结果时，处理顶部数据
     */
    private void handleTopContentData() {
        switch (mCurSceneType) {
            case BATTERY_LOW:
                resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.battery_icon);
                resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_battery);
                int extendTime = (int) NewResPageUtils.getExpandableTime(this.getContentResolver());
                resultPageData.putInt(ResultSingleCardLayout.EXTEND_TIME, extendTime);

                mFuncText = getString(R.string.landing_page_low_battery_func);
                mFuncTipText = getString(R.string.landing_page_low_battery_func_tip);
                mFuncIconId = R.drawable.icon_land_battery_fast;
                break;
            case BAT_SHARPDEC://短时间耗电过快
                ArrayList<ProcessItem> list = TKPubApi.getRunningProcesses(getApplication(), true);
                resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.speed_icon);
                resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_battery);
                resultPageData.putInt(ResultSingleCardLayout.APPS_COUNT, list.size());

                mFuncText = getString(R.string.battery_sharpdec_title_red);
                mFuncTipText = getString(R.string.landingpage_basharpdec_des);
                mFuncIconId = R.drawable.icon_land_battery_low;
                break;
            case NETFRQ_SCREENOFF:
                resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.screenoff_icon);
                resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_pillar);

                mFuncText = getString(R.string.netflow_screenoff_title);
                mFuncTipText = getString(R.string.landing_page_frequent_network_func_tip);
                mSingleAppTip = getString(R.string.landing_page_frequent_network_app_tip);
                mFuncIconId = R.drawable.landing_page_warning;
                break;
            case BG_CPU_OVERLOAD:
                ArrayList<ProcessItem> process = TKPubApi.getRunningProcesses(getApplication(), true);
                resultPageData.putInt(ResultSingleCardLayout.APPS_COUNT, process.size());
                resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.speed_icon);
                resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_battery);

                mFuncText = getString(R.string.backgroundtask_title, String.valueOf(process.size()));
                mFuncTipText = getString(R.string.landingpage_apps_des);
                mFuncIconId = R.drawable.icon_land_cpuhigh;
                break;
            case BG_MEM_OVERLOAD:
                ArrayList<ProcessItem> processlist = TKPubApi.getRunningProcesses(getApplication(), true);
                long memorySize = MemoryUtils.getAvailableRam(LandingPageGuideActivity.this, processlist);
                resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.speed_icon);
                resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_battery);
                resultPageData.putLong(ResultSingleCardLayout.MEM_COUNT, memorySize);

                mFuncText = getString(R.string.landing_page_mem_high_func);
                mFuncTipText = getString(R.string.landing_page_mem_high_func_tip);
                mFuncIconId = R.drawable.icon_land_ramhigh;
                break;
        }
    }

    private void initViews() {
        changeTitle(PRO_FOUND);

        mLoadingProgress = findViewById(R.id.loading);
        mFeatureContainer = findViewById(R.id.lp_feature_container);
        mGuideContainer = findViewById(R.id.lp_guide_container);
        mPerfectFrameLayout = findViewById(R.id.lp_loading_card_perfect_rl);
        mPerfectView = findViewById(R.id.lp_loading_card_perfect_view);

        mFuncIconView = findViewById(R.id.lp_top_panel_img_warn);
        mFuncTextView = findViewById(R.id.lp_top_panel_txt_warn);
        mFuncTipsView = findViewById(R.id.pull_to_refresh_text);
    }

    private void scanExistSingleApp(final String pkg) {
        new RunAsyncTask<Void, Void, AppInfoCompat>() {
            @Override
            protected AppInfoCompat doInBackground(Void... voids) {
                AppInfoCompat item = null;
                try {
                    item = AppManagerCompat.getAppInfo(pkg);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                return item;
            }

            @Override
            protected void onPostExecute(AppInfoCompat finalItem) {
                dismissProgressLoading();
                if (finalItem == null) {
                    completeAction();
                } else {
                    singleAppHandle(finalItem);
                }
            }
        }.execute();
    }

    private void scanExistMultiApp() {
        new RunAsyncTask<Void, Void, ArrayList<ProcessItem>>() {
            @Override
            protected ArrayList<ProcessItem> doInBackground(Void... voids) {
                ArrayList<ProcessItem> processItems = TKPubApi.getRunningProcesses(getApplication(), true);
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                }
                return processItems;
            }

            @Override
            protected void onPostExecute(ArrayList<ProcessItem> list) {
                dismissProgressLoading();
                multiAppHandle(list);
            }
        }.execute();
    }

    private void displayPerfectView() {
        mPerfectFrameLayout.setVisibility(View.VISIBLE);
        mPerfectView.addAnimatorListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                switch (getResultPageType()) {
                    case MultiCardPage:
                        sendEmptyMessage(R.id.msg_delay_display_multi_card, 500L);
                        break;
                    case SingleCardPage:
                        mFeatureContainer.setVisibility(View.GONE);
                        mPerfectView.setVisibility(View.GONE);
                        mPerfectFrameLayout.setVisibility(View.GONE);
                        startSingleCardSceneAnim(mCurSceneType, resultPageData);
                        break;
                    default:
                        break;
                }
            }
        });
        LottieAnimationUtil.loadLottieAnimation(this, mPerfectView, "function_complete", true);
    }

    @Override
    public void subHandleMessage(Message msg) {
        super.subHandleMessage(msg);
        //通过消息尽可能的拖延时间，提供广告加载
        if (msg.what == R.id.msg_delay_display_multi_card) {
            startMultiCardAnim();
        } else if (msg.what == R.id.msg_delay_display_perfect_view) {
            displayPerfectView();
        } else if (msg.what == R.id.msg_ad_landing_scene_loaded) {
            if (mCardListAdapter != null) {
                mCardListAdapter.notifyDataSetChanged();
            }
        }
    }

    private void multiAppHandle(List<ProcessItem> apps) {
        if (null == apps || apps.isEmpty()) {
            completeAction();
        } else {
            synchronized (LandingPageGuideActivity.class) {
                mCurMultiApps = apps;
            }
            handleTopContentData();
            showRunApps(apps, mFuncText, mFuncTipText);
        }
    }

    private void singleAppHandle(AppInfoCompat appInfo) {
        if (null == appInfo) {
            completeAction();
            return;
        }

        mCurSingleApp = appInfo;
        handleTopContentData();
        mFeatureContainer.setVisibility(View.VISIBLE);
        mFuncTextView.setText(Html.fromHtml(mFuncText));
        String label = appInfo.getLabel();
        mFuncTipsView.setText(Html.fromHtml(String.format(mFuncTipText, label)));
        View oneAppView = getLayoutInflater().inflate(R.layout.landing_page_app_run_back_one, null);

        Drawable drawable = appInfo.getIcon();
        if (null == drawable) {
            drawable = getResources().getDrawable(android.R.drawable.sym_def_app_icon);
        }
        if (mFuncIconId > 0) {
            mFuncIconView.setImageResource(mFuncIconId);
        }


        mSingleTopContainer = oneAppView.findViewById(R.id.lp_app_run_back_one_icon);
        ((ImageView) oneAppView.findViewById(R.id.lp_app_run_back_one_icon))
                .setImageDrawable(drawable);
        mBottomBtn = oneAppView.findViewById(R.id.bottom_content);
        mBottomBtn.setOnClickListener(this);

        mGuideContainer.removeAllViews();
        mGuideContainer.addView(oneAppView);

        View view = findViewById(R.id.root_content);
        if (view != null) {
            view.setBackgroundResource(R.drawable.single_result_bg);
        }
    }

    private void showRunApps(final List<ProcessItem> appList, final String wornText,
                             final String appsTips) {
        mFeatureContainer.setVisibility(View.VISIBLE);
        if (mFuncIconId > 0) {
            mFuncIconView.setImageResource(mFuncIconId);
        }
        mFuncTextView.setText(Html.fromHtml(wornText));
        mFuncTipsView.setText(Html.fromHtml(appsTips));
        mRunAppBackView = new LandingPageRunAppBackView(getApplicationContext());
        mBottomBtn = mRunAppBackView.findViewById(R.id.bottom_content);
        mBottomBtn.setOnClickListener(this);
        mGuideContainer.removeAllViews();
        mGuideContainer.addView(mRunAppBackView);
        mRunAppBackView.showRunApps(appList);

        View view = findViewById(R.id.root_content);
        if (view != null) {
            view.setBackgroundResource(R.drawable.single_result_bg);
        }
    }

    private void completeAction() {
        changeTitle(MORE_SUGGESTION);
        mFeatureContainer.setVisibility(View.GONE);
        sendEmptyMessage(R.id.msg_delay_display_perfect_view, 200L);
    }

    private void showProgressLoading() {
        mLoadingProgress.setVisibility(View.VISIBLE);
    }

    private void dismissProgressLoading() {
        mLoadingProgress.setVisibility(View.GONE);
    }

    private void cleanAndOptimizeApps() {
        new RunAsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                synchronized (LandingPageGuideActivity.class) {
                    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                    if (null != mCurMultiApps) {
                        for (int i = 0; i < mCurMultiApps.size(); i++) {
                            am.killBackgroundProcesses(mCurMultiApps.get(i).pkgName);
                        }
                    }
                }
                return false;
            }
        }.execute();

        mRunAppBackView.clearApps(new LandingPageRunAppBackView.ClearAppAnimListener() {

            @Override
            public void onAnimationEnd() {
                completeAction();
            }
        });
    }

    private void startSingleAnim() {
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_left_fade_out);
        animation.setAnimationListener(new AnimationListenerAdapter() {
            @Override
            public void onAnimationEnd(Animation animation) {
                super.onAnimationEnd(animation);
                completeAction();
            }
        });
        mSingleTopContainer.startAnimation(animation);
    }

    private void changeTitle(int status) {
        switch (status) {
            case PRO_FOUND:
                HeadHelper.setupMainHeader(this, R.id.main_title, R.string.landing_page_title_problem_found)
                        .hideSettingButton();
                break;
            case MORE_SUGGESTION:
                if (ResultPageSharedPrefManager.isCloudResultPageSwitch(this)) {
                    HeadHelper.setupMainHeader(this, R.id.main_title, R.string.landing_page_title_optimized)
                            .hideSettingButton();
                } else {
                    HeadHelper.setupMainHeader(this, R.id.main_title, R.string.landing_page_title_suggestion)
                            .hideSettingButton();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        liveTime = System.currentTimeMillis() - liveTime;
        dismissProgressLoading();
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onClick(View v) {
        if (v == mBottomBtn) {
            CardDataHelper.requestAd(EntranceType.LANDING_INTERSTITIAL);

            switch (mCurLayoutStyle) {
                case MULTI_APP_STYLE:
                    cleanAndOptimizeApps();
                    break;
                case SINGLE_APP_STYLE:
                    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                    am.killBackgroundProcesses(mCurSingleApp.pkgName);
                    startSingleAnim();
                    break;
                default:
                    completeAction();
                    break;
            }
            if (mCurSceneType != null) {
                FunctionItemSharedPrefs.setLandingPageHandingTime(this, mCurSceneType);
            }
        }
    }

}
